<?php


namespace App\Http\Controllers\Admin;


use App\Http\Common\BaseController;
use App\Http\Validator\LoginValidator;
use App\Models\Role;

use App\Models\User;
use App\Models\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;

class LoginController extends BaseController
{

    /**
     * 管理员邮箱登录
     * @param Request $request
     * @param LoginValidator $loginValidator
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function emailLogin(Request $request, LoginValidator $loginValidator)
    {
        $params = $request->only(['email', 'password']);

        //判断输入格式
        if (!$loginValidator->setScene('emailLogin')->check($params)) {
            return $this->returnJson(BaseController::FIELD_ERROR, $loginValidator->getError());
        }

        //判断用户是否存在
        $userInfo = User::where([
            'email' => $params['email'],
            'password' => md5($params['password'])
        ])->first();
        if (!$userInfo) return $this->returnJson(BaseController::DATA_NOTFOUND, '输入的管理员不存在');

        //销毁管理员的token
        if (Redis::get($userInfo['email_token'])){
            Redis::del($userInfo['email_token']);
        }

        //生成token
        $token = $this->tokenPrefix . $this->makeToken($userInfo['id']);

        //用户信息
        $info = [
            'id' => $userInfo['id'],
            'username' => $userInfo['username'],
            'phone' => $userInfo['phone'],
            'type'  => 1
        ];

        //存储用户信息
        Redis::setex($token, 60 * 60 * 24, json_encode($info));

        User::where('id', $userInfo['id'])->update(['email_token' => $token]);
        User::where('id', $userInfo['id'])->update(['email_date' => time()]);

        return $this->returnJson(BaseController::SUCCESS, '登录成功', [
            'token'     => $token,
        ]);
    }
}
